package com.itheima.web.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Freeze;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.UnFreeze;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.FreeService;
import com.itheima.service.mongo.MovementService;
import com.itheima.vo.CommentVo;
import com.itheima.vo.MovementVo;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import static java.time.Duration.*;

@Component
public class UserManager {

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private UserService userService;

    // 用户列表
    public ResponseEntity findUserInfoByPage(Integer pageNum, Integer pageSize) {
        // 1.rpc查询
        PageBeanVo pageBeanVo = userInfoService.findByPage(pageNum, pageSize);
        // 2.返回
        return ResponseEntity.ok(pageBeanVo);
    }

    // 用户详情
    public ResponseEntity findUserInfoById(Long userId) {
        // 1 .查询userInfo
        UserInfo userInfo = userInfoService.findByUserId(userId);

        if (stringRedisTemplate.opsForValue().get("freeze:") == null) {
            userInfo.setUserStatus("1");
            userInfo.setId(userId);

            User user = new User();
            user.setUserStatus("1");
            user.setId(userId);

            userService.update(user);
            userInfoService.update(userInfo);
        }


        // 2.返回userInfo
        return ResponseEntity.ok(userInfo);
    }

    @DubboReference
    private MovementService movementService;

    // 动态列表
    public ResponseEntity messages(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        // 1.调用rpc查询
        PageBeanVo pageBeanVo = movementService.findMovementByPage(userId, state, pageNum, pageSize);
        // 2.封装vo
        // 2-1 声明voList
        List<MovementVo> voList = new ArrayList<>();
        // 2-2 获取movementList
        List<Movement> movementList = (List<Movement>) pageBeanVo.getItems();
        // 2-3 遍历movementList
        if (CollectionUtil.isNotEmpty(movementList)) {
            for (Movement movement : movementList) {
                // 查询userInfo
                UserInfo userInfo = userInfoService.findByUserId(movement.getUserId());
                // 创建vo
                MovementVo vo = new MovementVo();
                vo.setUserInfo(userInfo);
                vo.setMovement(movement);
                // 自定义时间格式   yyyy-MM-dd HH:mm:ss
                vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));
                // 添加集合
                voList.add(vo);
            }
        }
        // 3.voList设置到集合
        pageBeanVo.setItems(voList);

        // 4.返回分页
        return ResponseEntity.ok(pageBeanVo);
    }

    // 单条动态
    public ResponseEntity findMovementVoById(String publishId) {
        // 1.调用rpc查询
        Movement movement = movementService.findById(new ObjectId(publishId));
        // 2.封装vo
        // 查询userInfo
        UserInfo userInfo = userInfoService.findByUserId(movement.getUserId());
        // 创建vo
        MovementVo vo = new MovementVo();
        vo.setUserInfo(userInfo);
        vo.setMovement(movement);
        // 自定义时间格式   yyyy-MM-dd HH:mm:ss
        vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));
        // 3.返回结果
        return ResponseEntity.ok(vo);
    }

    @DubboReference
    private CommentService commentService;
    // 动态评论列表
    public ResponseEntity findCommentVoByPage(String publishId, Integer pageNum, Integer pageSize) {
        // 1.查询评论列表
        PageBeanVo pageBeanVo = commentService.findCommentByPage(new ObjectId(publishId), 2, pageNum, pageSize);
        // 2. 封装commentVo
        // 2-1 声明voList
        List<CommentVo> voList = new ArrayList<>();
        // 2-2 获取commentList
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        // 2-3 遍历commentList
        if (CollectionUtil.isNotEmpty(commentList)) {
            for (Comment comment : commentList) {
                // 查询userInfo
                UserInfo userInfo = userInfoService.findByUserId(comment.getUserId());
                // 创建vo
                CommentVo vo = new CommentVo();
                vo.setId(comment.getId().toHexString()); // 评论id
                vo.setAvatar(userInfo.getAvatar());// 评论人头像
                vo.setNickname(userInfo.getNickname()); // 评论人昵称
                vo.setContent(comment.getContent());// 评论内容
                vo.setCreateDate(DateUtil.formatTime(new Date(comment.getCreated())));// 评论时间
                // 添加到list
                voList.add(vo);

            }
        }
        // 3.将voList设置到分页对象
        pageBeanVo.setItems(voList);

        // 4.返回分页对象
        return ResponseEntity.ok(pageBeanVo);

    }

    //冻结用户
    @DubboReference
    private FreeService freeService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ResponseEntity freeze(Freeze freeze) {

        //调用rpc保存到freeze_user表
        freeService.saveFreezeUser(freeze);

        //更新db表中的user,status字段的值
        Integer userId = freeze.getUserId();

        User user = new User();
        user.setId(Long.valueOf(userId));

        UserInfo userInfo = new UserInfo();
        userInfo.setId(Long.valueOf(userId));

        if (freeze.getFreezingTime() ==1){//冻结3天

            stringRedisTemplate.opsForValue().set("freeze:", user.toString(), Duration.ofDays(3));

            //更新db表中的userInfo,status字段的值
            user.setUserStatus("2");
            userInfo.setUserStatus("2");
        }else if (freeze.getFreezingTime() ==2){//冻结7天

            stringRedisTemplate.opsForValue().set("freeze:", user.toString(), Duration.ofDays(5));

            user.setUserStatus("2");
            userInfo.setUserStatus("2");

        }else if (freeze.getFreezingTime() ==3){//永久冻结

            stringRedisTemplate.opsForValue().set("freeze:", user.toString(), Duration.ofDays(10000));

            user.setUserStatus("2");
            userInfo.setUserStatus("2");
        }


        if (freeze.getFreezingRange() == 1){//冻结登录

            stringRedisTemplate.opsForValue().set("freeze:login", "1");
        }else if (freeze.getFreezingRange() == 2){//冻结发言

            stringRedisTemplate.opsForValue().set("freeze:say", "2");

        }else if (freeze.getFreezingRange() == 3 ){//冻结发布动态

            stringRedisTemplate.opsForValue().set("freeze:publish", "3");
        }

        userService.update(user);
        userInfoService.update(userInfo);

        return ResponseEntity.ok("操作成功");
    }

    //解除冻结
    public ResponseEntity unfreeze(UnFreeze unFreeze) {

        freeService.deleteFreezeUser(unFreeze);

        stringRedisTemplate.delete("freeze:login");
        stringRedisTemplate.delete("freeze:say");
        stringRedisTemplate.delete("freeze:publish");

        //也要对db的两个表同时解除冻结
        Integer userId = unFreeze.getUserId();

        User user = new User();
        UserInfo userInfo = new UserInfo();

        user.setId(Long.valueOf(userId));
        userInfo.setId(Long.valueOf(userId));

        user.setUserStatus("1");
        userInfo.setUserStatus("1");

        userService.update(user);
        userInfoService.update(userInfo);

        return ResponseEntity.ok("操作成功");
    }


    //动态复审
    public void messagesReview(List<String> param) {
        for (String publishId : param) {
            //查询动态列表
            Movement movement = movementService.findById(new ObjectId(publishId));
            movement.setState(1);
            movementService.update(movement);
        }


    }

    //动态复审拒绝
    public void messagesReviewFalse(List<String> param) {

        for (String publishId : param) {
            Movement movement = movementService.findById(new ObjectId(publishId));
            movement.setState(2);
            movementService.update(movement);
        }
    }


}
